function X_filtered = ecg_bandpass(X,Fp=[0.5 100],Rs=10,Samp_freq=550)
%% Bandpass filter for ECG
% Usage:
% X_filtered = ecg_bandpass(X);
% X_filtered = ecg_bandpass(X, [Fp1 Fp2]);
% X_filtered = ecg_bandpass(X, [Fp1 Fp2], Rs);
% X_filtered = ecg_bandpass(X, [Fp1 Fp2], Rs, Samp_freq);
%
% Inputs:
% X: Discrete time signal
% [Fs1,Fs2]: Stop band (notch) in Hz
% Rs: Maximiumm attenuation in the stop band (notch) in dB
% Samp_freq: Sampling frequency of the signalin Hz
% 
% Outputs:
% X_filtered: filtered signal
%
% Warnings:
% Do not overdesign the chebyshev type I filter; filtfilt() may fail if the filter order is larger than 5
%
% Debug mode:
% If output variable is not specified, debug mode will automatically turned on.
% Filtered signal and Frequencncy response of the notch filter will be drawn in new figure window.
%
% Copyright by Group 8

%Define filter requirements
Wp =  Fp / Samp_freq *2;
Ws = [0 Fp(2)*1.5]/Samp_freq*2;
Rp = 1;

%generate cheby1 filter
[n Wc] = cheb1ord(Wp,Ws,Rp,Rs);
if(n>=5)
	printf('Warning: Order n>=5, seems to overdesign bandpass filters\n');
end

[b,a]=cheby1(n,Rp,Wc);

%filter signal
X_filtered = filtfilt(b,a,X);

%Debug:
if(!nargout)
figure(1)
freqz(b,a,512,Samp_freq);
figure(2);
t = [0:length(X)-1]/550;
subplot(2,1,1), plot(t,X,';Raw signal;'),xlim([15 25])
ylabel('Voltage / V')
subplot(2,1,2), plot(t,X_filtered,';Filtered signal;'),xlim([15 25])
xlabel('time / s');
end

end
